import type { FormInstance } from 'ant-design-vue'
import type { SelectValue } from 'ant-design-vue/es/select'
import { createTenant, getCompanyList } from '@/apis/tenant'
import { Button, Drawer, Form, FormItem, Input, message, Select, Space, Textarea } from 'ant-design-vue'

export default defineComponent({
  emits: ['success'],
  setup(_, { expose, emit }) {
    const open = ref(false)
    const loading = ref(false)
    const formRef = useTemplateRef<FormInstance>('formRef')
    const formState = reactive<{
      tenantName: string
      tenantDesc: string
      companyId: SelectValue
    }>({
      tenantName: '',
      tenantDesc: '',
      companyId: undefined,
    })
    const rules = {
      tenantName: [{ required: true, message: '请输入租户名称' }],
      tenantDesc: [{ required: true, message: '请输入租户描述' }],
      companyId: [{ required: true, message: '请选择所属公司' }],
    }
    const companyList = ref<any[]>([])
    async function onSubmit() {
      try {
        await formRef.value?.validate()
        loading.value = true
        const res = await createTenant(formState)
        if (res.status === 0) {
          message.success('创建成功')
          open.value = false
          emit('success')
        }
        else {
          message.error(res.msg)
        }
      }
      finally {
        loading.value = false
      }
    }
    expose({
      open() {
        open.value = true
      },
    })
    onMounted(async () => {
      const res = await getCompanyList()
      companyList.value = res.data.options
    })
    return () => (
      <Drawer open={open.value} width="40%" title="添加租户" onClose={() => (open.value = false)}>
        <Form ref="formRef" model={formState} rules={rules}>
          <FormItem label="租户名称" name="tenantName">
            <Input value={formState.tenantName} onUpdate:value={value => (formState.tenantName = value)} placeholder="请输入租户名称" />
          </FormItem>
          <FormItem label="所属企业" name="companyId">
            <Select value={formState.companyId} onUpdate:value={value => (formState.companyId = value)} placeholder="请选择所属企业" options={companyList.value} />
          </FormItem>
          <FormItem label="租户描述" name="tenantDesc">
            <Textarea value={formState.tenantDesc} onUpdate:value={value => (formState.tenantDesc = value as string)} rows={4} placeholder="请输入租户描述" />
          </FormItem>
          <FormItem wrapperCol={{ span: 18, offset: 4 }}>
            <Space class="w-full flex justify-end">
              <Button onClick={() => open.value = false}>
                取消
              </Button>
              <Button loading={loading.value} type="primary" onClick={onSubmit}>
                提交
              </Button>
            </Space>
          </FormItem>
        </Form>
      </Drawer>
    )
  },
})
